<template>
    <!-- CAD右侧列表 -->
    <div class="lay-root">
        <div class="select-lay">
            <div class="select-name">
                {{ $t("message.cadViewer.ballRelationTable.selectTitle") }}:
            </div>

            <el-select v-model="selectValue" :placeholder="$t('message.cadViewer.ballRelationTable.selectHold')
                " class="samll-ipt" @change="onSelectChange" :disabled="isEditMde">
                <el-option v-for="item in selectOptions.slice(0, selectType == 1 ? 2 : 1)" :key="item.value"
                    :label="item.label" :value="item.value" :min-width="item.minWidth">
                </el-option>
            </el-select>
        </div>

        <div class="lay-cutoff"></div>

        <el-table :data="tableData" :border="true" :stripe="false" height="200" ref="singleTable" highlight-current-row
            @current-change="handleCurrentChange" :header-cell-style="{
                color: 'rgba(0, 0, 0, 0.85)',
                fontSize: '14px',
                fontWeight: 'bold',
                padding: 0,
                height: '32px',
                background: '#edeeef',
            }" :cell-style="{
                color: 'rgba(96,98,102,1)',
                fontSize: '14px',
                padding: 0,
                height: '32px',
            }" :row-style="{
                color: 'rgba(96,98,102,1)',
                fontSize: '13px',
                padding: '10px 20px',
                height: '32px',
            }">
            <el-table-column :prop="tableHeadData[0].prop" :label="tableHeadData[0].colLabel"
                :width="tableHeadData[0].width" :align="tableHeadData[0].align"
                :header-align="tableHeadData[0].headerAlign">
            </el-table-column>
            <el-table-column :prop="tableHeadData[1].prop" :label="tableHeadData[1].colLabel"
                :width="tableHeadData[1].width" :align="tableHeadData[1].align"
                :header-align="tableHeadData[1].headerAlign">
            </el-table-column>

            <el-table-column :prop="tableHeadData[2].prop" :label="tableHeadData[2].colLabel"
                :width="tableHeadData[2].width" :align="tableHeadData[2].align"
                :header-align="tableHeadData[2].headerAlign">
                <template slot-scope="scope">
                    <!-- <img style="width:40px;height:40px;padding:10px" :src="" alt="" /> -->

                    <img style="width: 40px; height: 40px; padding: 10px" :src="scope.row.flag ? checkImg : uncheckImg"
                        alt="" />

                    <!-- <i class="iconfont" style="color:#0000ff;">{{scope.row.checked ? '\ue97f': '\ue980'  }}</i> -->

                    <!-- <div class="remarks">
                        <el-checkbox
                            v-model="scope.row.checked"
                            disabled="true"
                        ></el-checkbox>
                    </div> -->
                </template>
            </el-table-column>

            <!-- <el-table-column
                :prop="tableHeadData[3].prop"
                :label="tableHeadData[3].colLabel"
                :width="tableHeadData[3].width"
                :align="tableHeadData[3].align"
                :header-align="tableHeadData[3].headerAlign"
            >
                <template slot-scope="scope">

                    <img
                        style="width: 40px; height: 40px; padding: 10px"
                        :src="checkImg"
                        alt=""
                    />

                </template> -->
            </el-table-column>
        </el-table>

        <div class="footer-lay">
            <div class="footer-texe">
                {{
                    $t("message.cadViewer.ballRelationTable.footerText") +
                    tableData.length +
                    $t("message.cadViewer.ballRelationTable.footerUnit")
                }}
            </div>

            <!-- footerText: `件数=`,
            footerUnit: `件` -->
        </div>
    </div>
</template>

<script>
import {
    getThckFixedPoint,
    getThckMark,
    getPartsMark,
    getVisualFixedPoint,
    getPartsFixedPoint,
    getVisualMark,
    updThckMark,
    updPartsMark,
    updVisualMark,
} from "../../api/api";
export default {
    // props: {
    //     // 1 壁厚  2 目视
    //     selectType: Number,
    //     macNumb: String,
    //     macCode: String,
    //     isEditMde: Boolean,
    // },
    props: ["selectType", "macNumb", "macCode", "isEditMde", "optPltCode"],

    data() {
        let _self = this;
        return {
            tableHeadData: [
                {
                    index: 0,
                    colLabel: this.$t(
                        "message.cadViewer.ballRelationTable.tableHeads[0]"
                    ),
                    prop: "posOrdr",
                    width: 65,
                    align: "center",
                    headerAlign: "center",
                },
                {
                    index: 2,
                    colLabel: this.$t(
                        "message.cadViewer.ballRelationTable.tableHeads[1]"
                    ),
                    prop: "posName",
                    minWidth: "30%",
                    align: "left",
                    headerAlign: "left",
                },
                {
                    index: 1,
                    colLabel: this.$t(
                        "message.cadViewer.ballRelationTable.tableHeads[2]"
                    ),
                    prop: "flag",
                    width: 90,
                    align: "center",
                    headerAlign: "center",
                },
                {
                    index: 3,
                    colLabel: "3D",
                    prop: "flag",
                    width: 90,
                    align: "center",
                    headerAlign: "center",
                },
            ],

            tableData: [],
            checkImg: require("@/assets/img/checkbox_sel.png"),
            uncheckImg: require("@/assets/img/checkbox_unsel.png"),

            selectValue: 1,
            selectOptions: [
                {
                    des: "pointMarkup",
                    value: 1,
                    label: _self.$t(
                        "message.cadViewer.ballRelationTable.selectTypePoint"
                    ),
                },
                {
                    des: "pointMarkup",
                    value: 2,
                    label: _self.$t(
                        "message.cadViewer.ballRelationTable.selectTypeGroup"
                    ),
                },
            ],

            markupList: [],
            selectTableItem: null,
            isJustSelectTableItemNotCallback: false,
        };
    },

    watch: {
        selectType(nVal) {
            console.log(nVal, "wwwwwwwwwww1")
            this.selectValue = 1;
            this.initTableAndMarkups();
        },

        isEditMde(nVal) {
            console.log(nVal, "wwwwwwwwwww2")
            // this.$refs.singleTable.setCurrentRow(this.tableData[0]);
        },
    },

    created() {
        // this.initTableAndMarkups();
    },

    methods: {
        initTableAndMarkups() {
            if (this.selectType == 1) {
                this.getThckMarkApi();
            } else if (this.selectType == 3) {
                this.getPartsMarkApi();
            } else {
                this.getVisualMarkApi();
            }
        },

        handleCurrentChange(e) {
            console.log(e);
            this.selectTableItem = e;
            if (!this.isJustSelectTableItemNotCallback)
                this.$emit("onTableItemSelect", e);
            this.isJustSelectTableItemNotCallback = false;
        },

        onSelectChange(e) {
            this.initTableAndMarkups();
        },

        /**
         * 获取壁厚的点位列表
         */
        getThckFixedPointApi() {
            let _self = this;
            let dataJson = {
                macNumb: this.macNumb,
                blnKbn: this.selectValue,
            };
            getThckFixedPoint(dataJson).then((res) => {
                console.log(res);
                if (!res.data.data || !res.data.data.length) {
                    res.data.data = [];
                }
                _self.tableData = res.data.data;
                if (_self.tableData.length > 0)
                    _self.$refs.singleTable.setCurrentRow(_self.tableData[0]);
            });
        },

        /**
         * 获取目视的点位列表
         */
        getVisualFixedPointApi() {
            let _self = this;
            let dataJson = {
                dmgCode: Number(this.macCode),
            };
            getVisualFixedPoint(dataJson).then((res) => {
                console.log(res);
                if (!res.data.data || !res.data.data.length) {
                    res.data.data = [];
                }

                res.data.data.forEach((e) => {
                    e.posOrdr = e.posNo;
                });

                _self.tableData = res.data.data;
                if (_self.tableData.length > 0)
                    _self.$refs.singleTable.setCurrentRow(_self.tableData[0]);
            });
        },

        getPartsFixedPointApi() {
            let _self = this;
            let dataJson = {
                dmgCode: Number(this.macCode),
            };
            getPartsFixedPoint(dataJson).then((res) => {
                console.log(res);
                if (!res.data.data || !res.data.data.length) {
                    res.data.data = [];
                }

                res.data.data.forEach((e) => {
                    e.posOrdr = e.posNo;
                });

                _self.tableData = res.data.data;
                if (_self.tableData.length > 0)
                    _self.$refs.singleTable.setCurrentRow(_self.tableData[0]);
            });
        },

        getThckMarkApi() {
            let _self = this;
            let dataJson = {
                macNumb: this.macNumb,
                blnKbn: this.selectValue,
                dmgCode: Number(this.macCode),
                pltCode: Number(this.optPltCode),
            };
            getThckMark(dataJson).then((res) => {
                console.log(res);
                if (!res.data.data || !res.data.data.length) {
                    res.data.data = [];
                }
                try {
                    res.data.data.forEach(item => {
                        item.poS_ORDR_Clone = item.poS_ORDR
                        item.poS_ORDR = Number(item.num)
                    })
                } catch (error) {

                }
                let tempList = this.genThckBallMarkupsList(res.data.data);
                this.markupList = tempList;
                console.log(tempList);
                _self.$emit("updateBallMarkups", tempList);
                _self.getThckFixedPointApi();
            });
        },

        getPartsMarkApi() {
            let _self = this;
            let dataJson = {
                dmgCode: Number(this.macCode),
                pltCode: Number(this.optPltCode),
            };
            getPartsMark(dataJson).then((res) => {
                console.log(res);
                if (
                    !res.data.data.visualMarkDetials ||
                    !res.data.data.visualMarkDetials.length
                ) {
                    res.data.data.visualMarkDetials = [];
                }
                try {
                    res.data.data.visualMarkDetials.forEach(item => {
                        item.poS_ORDR_Clone = item.poS_NO
                        item.poS_NO = Number(item.num)
                    })
                    console.log('res.data.data.visualMarkDetials', res.data.data.visualMarkDetials);

                } catch (error) {

                }
                let tempList = this.genVisualBallMarkupsList(
                    res.data.data.visualMarkDetials
                );
                this.markupList = tempList;
                console.log('tempList', tempList);
                _self.$emit("updateBallMarkups", tempList);
                _self.getPartsFixedPointApi();
            });
        },

        getVisualMarkApi() {
            let _self = this;
            let dataJson = {
                dmgCode: Number(this.macCode),
                pltCode: Number(this.optPltCode),
            };
            getVisualMark(dataJson).then((res) => {
                console.log(res);
                if (
                    !res.data.data.visualMarkDetials ||
                    !res.data.data.visualMarkDetials.length
                ) {
                    res.data.data.visualMarkDetials = [];
                }
                try {
                    res.data.data.visualMarkDetials.forEach(item => {
                        item.poS_ORDR_Clone = item.poS_NO
                        item.poS_NO = Number(item.num)
                    })
                } catch (error) {

                }
                let tempList = this.genVisualBallMarkupsList(
                    res.data.data.visualMarkDetials
                );
                this.markupList = tempList;
                console.log(tempList);
                _self.$emit("updateBallMarkups", tempList);
                _self.getVisualFixedPointApi();
            });
        },

        updThckMarkApi() {
            let tempData = this.genUpdateReturnData(true);
            tempData.dmgCode = Number(this.macCode)
            tempData.pltCode = Number(this.optPltCode)

            updThckMark(tempData).then((res) => {
                console.log(res);
                if (res.data.code != 0) {
                    this.$alert(res.data.msg, '', {
                        confirmButtonText: 'OK',
                        type: 'warning',
                    });
                    return
                }
                this.$message({
                    type: 'success',
                    message: res.data.msg
                })
                this.initTableAndMarkups();
            });
        },

        updPartsMarkApi() {
            let tempData = this.genUpdateReturnData(true);
            tempData.dmgCode = Number(this.macCode)
            tempData.pltCode = Number(this.optPltCode)
            updPartsMark(tempData).then((res) => {
                console.log(res);
                if (res.data.code != 0) {
                    this.$alert(res.data.msg, '', {
                        confirmButtonText: 'OK',
                        type: 'warning',
                    });

                    return
                }
                this.$message({
                    type: 'success',
                    message: res.data.msg
                })
                this.initTableAndMarkups();
            });
        },

        updVisualMarkApi() {
            let tempData = this.genUpdateReturnData(true);
            tempData.dmgCode = Number(this.macCode)
            tempData.pltCode = Number(this.optPltCode)
            updVisualMark(tempData).then((res) => {
                console.log(res);
                if (res.data.code != 0) {
                    this.$alert(res.data.msg, '', {
                        confirmButtonText: 'OK',
                        type: 'warning',
                    });

                    return
                }
                this.$message({
                    type: 'success',
                    message: res.data.msg
                })
                this.initTableAndMarkups();
            });
        },

        genVisualBallMarkupsList(originData) {
            let reList = [];
            for (let i = 0; i < originData.length; i++) {
                let originItem = originData[i];
                let reListLength = reList.length;
                let reListLastItem =
                    reListLength > 0 ? reList[reListLength - 1] : null;

                // 新建一个球标组 球标数组为空 新位置节点与原球标组pos_no不同
                if (
                    reListLength == 0 ||
                    reListLastItem.pos_no != originItem.poS_NO ||
                    (reListLastItem.pos_no == originItem.poS_NO &&
                        (reListLastItem.bln_kbn != originItem.blN_KBN ||
                            reListLastItem.bln_dtlno != originItem.blN_DTLNO))
                ) {
                    let ballTemp = {};
                    ballTemp.sId = originItem.poS_NO;
                    ballTemp.shapeType = Number(originItem.blN_TYPE) + 12;
                    ballTemp.showType = "trans";
                    ballTemp.showID = originItem.poS_NO;
                    ballTemp.lineColor = "#0000ff";
                    ballTemp.lineWidth = "5";
                    ballTemp.fontSize = originItem.blN_FNTSIZ;
                    ballTemp.fontName = originItem.blN_FNTNAM;
                    ballTemp.lineStyle = "0";
                    ballTemp.points = [];
                    ballTemp.bln_kbn = originItem.blN_KBN;
                    ballTemp.bln_dtlno = originItem.blN_DTLNO;

                    ballTemp.pos_no = originItem.poS_NO;
                    // ballTemp.pos_no1 = originItem.poS_NO;
                    ballTemp.allText = originItem.poS_ORDR_Clone;
                    ballTemp.ballFillColor = "#00000000";

                    ballTemp.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });

                    reList.push(ballTemp);
                } else {
                    reListLastItem.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });
                }
            }
            return reList;
        },

        genThckBallMarkupsList(originData) {
            let reList = [];
            for (let i = 0; i < originData.length; i++) {
                let originItem = originData[i];
                let reListLength = reList.length;
                let reListLastItem =
                    reListLength > 0 ? reList[reListLength - 1] : null;

                // 新建一个球标组 球标数组为空 新位置节点与原球标组pos_no不同
                if (
                    reListLength == 0 ||
                    reListLastItem.pos_no != originItem.poS_ORDR ||
                    (reListLastItem.pos_no == originItem.poS_ORDR &&
                        (reListLastItem.bln_kbn != originItem.blN_KBN ||
                            reListLastItem.bln_dtlno != originItem.blN_DTLNO))
                ) {
                    let ballTemp = {};
                    ballTemp.sId = originItem.poS_ORDR;
                    ballTemp.shapeType = Number(originItem.blN_TYPE) + 12;
                    ballTemp.showType = "trans";
                    ballTemp.showID = originItem.poS_ORDR;
                    ballTemp.lineColor = "#0000ff";
                    ballTemp.lineWidth = "5";
                    ballTemp.fontSize = originItem.blN_FNTSIZ;
                    ballTemp.fontName = originItem.blN_FNTNAM;
                    ballTemp.lineStyle = "0";
                    ballTemp.points = [];
                    ballTemp.bln_kbn = originItem.blN_KBN;
                    ballTemp.bln_dtlno = originItem.blN_DTLNO;

                    ballTemp.pos_no = originItem.poS_ORDR;
                    ballTemp.allText = originItem.poS_ORDR_Clone;
                    ballTemp.ballFillColor = "#00000000";

                    ballTemp.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });

                    reList.push(ballTemp);
                } else {
                    reListLastItem.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });
                }
            }
            return reList;
        },

        genUpdateReturnData(flg = false) {
            let re = [];
            let tempAuto = 1;
            this.markupList.forEach((listE) => {
                listE.points.forEach((e) => {
                    let temp = {};
                    if (this.selectType == 1) {
                        temp = {
                            dmgCode: Number(this.macCode),
                            autoNo: tempAuto++,
                            posOrdr: listE.pos_no, // ?
                            grnPosNo: 0,
                            blnKbn: this.selectValue,
                            blnType: Number(listE.shapeType) - 12,
                            blnWidth: Number(listE.lineWidth),
                            blnFntsiz: Number(listE.fontSize),
                            blnFntnam: listE.fontName,
                            blnX: String(e.x),
                            blnY: String(e.y),
                            blnDtlNo: listE.bln_dtlno,
                            //     blnDtlNo: 1,
                        };
                    } else {
                        temp = {
                            dmgCode: Number(this.macCode),
                            autoNo: tempAuto++,
                            posNo: listE.pos_no, // ?

                            blnType: Number(listE.shapeType) - 12,
                            blnWidth: Number(listE.lineWidth),
                            blnFntsiz: Number(listE.fontSize),
                            blnFntnam: listE.fontName,
                            blnX: String(e.x),
                            blnY: String(e.y),
                            blnDtlNo: listE.bln_dtlno,
                            //     blnDtlNo: 1,
                        };
                    }

                    re.push(temp);
                });
            });
            console.log(this.selectValue, "###########");

            if (flg) {
                re = {
                    blnKbn: this.selectValue,
                    dataList: re
                }
            }
            return re;
        },

        toSelectTableItem(inData) {
            for (let i = 0; i < this.tableData.length; i++) {
                if (this.tableData[i].posOrdr == inData) {
                    // 不重复选中 避免相同的选中item不能触发选中回调，导致isJustSelectTableItemNotCallback无法复位
                    if (
                        this.tableData[i].posOrdr ==
                        this.selectTableItem.posOrdr
                    )
                        break;

                    this.isJustSelectTableItemNotCallback = true;
                    this.$refs.singleTable.setCurrentRow(this.tableData[i]);
                    //     this.selectTableItem = this.tableData[i];
                    break;
                }
            }
        },

        deleteBallMarkup(inOrder, inKbn) {
            let arr = [
                { id: 1, type: 1 },
                { id: 2, type: 2 },
                { id: 3, type: 3 },
                { id: 4, type: 1 },
            ];

            let filteredArr = arr.filter(item => {
                return item.id !== 1 && item.type !== 1
            });

            console.log(filteredArr);
            console.log(this.markupList, inOrder, inKbn);
            for (let i = 0; i < this.markupList.length; i++) {
                let tempMarkItem = this.markupList[i];
                if (
                    tempMarkItem.pos_no == inOrder &&
                    tempMarkItem.bln_dtlno == inKbn
                ) {
                    this.markupList.splice(i, 1);
                    break;
                }
            }
            // this.markupList = this.markupList.filter(item => item.pos_no != inOrder && item.bln_dtlno != inKbn)
            console.log(this.markupList, inOrder, inKbn);

            this.updateTableState();
        },

        updateTableState() {
            let _self = this;
            this.tableData.forEach((tableE) => {
                let temp = tableE.posOrdr;
                var tempItem = null;
                tempItem = _self.markupList.find((item, index) => {
                    return item.pos_no == temp;
                });

                if (tempItem) {
                    tableE.flag = 1;
                } else {
                    tableE.flag = 0;
                }
            });
        },

        setOnAddMarkupData(inData) {
            console.log(inData, "DDDDDDDDD")
            if (inData == null) return;
            // if(inData.bln_kbn > 0 && inData.posOrder > 0)
            let haveTemp = null;
            if (this.selectType == 1) {
                haveTemp = this.markupList.find((item, index) => {
                    return (
                        item.pos_no == inData.posOrder &&
                        item.bln_kbn == inData.bln_kbn &&
                        item.bln_dtlno == inData.bln_dtlno
                    );
                });
            } else if (this.selectType == 2 || this.selectType == 3) {
                haveTemp = this.markupList.find((item, index) => {
                    return (
                        item.pos_no == inData.posOrder &&
                        item.bln_dtlno == inData.bln_dtlno
                    );
                });
            }

            if (haveTemp) {
                haveTemp.fontSize = inData.selectedFontSize;
                haveTemp.fontName = inData.selectedFont;

                haveTemp.points = [];
                inData.pointList.forEach((e) => {
                    haveTemp.points.push({
                        bln_x: e.x,
                        bln_y: e.y,
                        x: e.x,
                        y: e.y,
                    });
                });
            } else {
                let tempOrder = this.selectTableItem.posOrdr;
                let maxKbn = 0;
                this.markupList.forEach((e) => {
                    if (e.pos_no == tempOrder && e.bln_kbn > maxKbn) {
                        maxKbn = e.bln_kbn;
                    }
                });

                let maxDtlno = 0;
                this.markupList.forEach((e) => {
                    if (e.pos_no == tempOrder && e.bln_dtlno > maxDtlno) {
                        maxDtlno = e.bln_dtlno;
                    }
                });

                let ballTemp = {};
                ballTemp.sId = tempOrder;
                ballTemp.shapeType = inData.fEntType;
                ballTemp.showType = "trans";
                ballTemp.showID = tempOrder;
                ballTemp.lineColor = "#0000ff";
                ballTemp.lineWidth = "5";
                ballTemp.fontSize = inData.selectedFontSize;
                ballTemp.fontName = inData.selectedFont;
                ballTemp.lineStyle = "0";
                //     ballTemp.points = [];
                ballTemp.bln_kbn = maxKbn + 1;
                ballTemp.bln_dtlno = maxDtlno + 1;
                ballTemp.pos_no = tempOrder;
                ballTemp.ballFillColor = "#00000000";

                ballTemp.points = [];
                inData.pointList.forEach((e) => {
                    ballTemp.points.push({
                        bln_x: e.x,
                        bln_y: e.y,
                        x: e.x,
                        y: e.y,
                    });
                });
                console.log(ballTemp, "BBBBBBBBBBBBBBBBbb")
                this.markupList.push(ballTemp);
                console.log(this.markupList, "MMMMMMMMMMMMM")
                this.updateTableState();
                this.$emit("updateBallMarkups", this.markupList);
            }

            this.genUpdateReturnData();
        },

        exitBallMode(inMode) {
            console.log('inMode', inMode);
            if (inMode == 0) {
                if (this.selectType == 1) {
                    this.updThckMarkApi();
                } else if (this.selectType == 3) {
                    this.updPartsMarkApi();
                } else {
                    this.updVisualMarkApi();
                }
                this.$emit('showExitMarkupDialogFn')

            } else if (inMode == 1) {
                // this.initTableAndMarkups();
                this.$emit('showExitMarkupDialogFn')
            } else if (inMode == 2) {
                this.initTableAndMarkups();
                this.$emit('showExitMarkupDialogFn')
            }
        },

        getTableListCount() {
            return this.tableData.length;
        },
    },
};
</script>

<style scoped lang="scss">
.lay-root {
    background-color: darkgray;
    border: 1px solid #c3c3c3;
    display: flex;
    flex-direction: column;
}

.lay-cutoff {
    width: 100%;
    height: 1px;
    background-color: #e8e8e8;
}

.select-lay {
    //   width: 480px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 10px 50px;
    background-color: #edeeef;

    .select-name {
        font-size: 14px;
        font-weight: 900;
        color: rgba(0, 0, 0, 0.85);
    }
}

.samll-ipt {
    ::v-deep .el-input__inner {
        height: 24px;
    }

    ::v-deep .el-input__icon {
        line-height: 24px;
    }
}

.footer-lay {
    width: 100%;
    height: 38px;
    background: #edeeef;

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;

    .footer-texe {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
    }
}
</style>